package src

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
)

func sendMsg(title, msg, comment, warning string) {
	var params = make([]string, 0)
	params = append(params, fmt.Sprintf("title=(%s)-%s", time.Now().Local().Format("20060102_15:04:05"), title))
	if len(comment) > 0 {
		params = append(params, "comment="+comment)
	}
	if len(warning) > 0 {
		params = append(params, "warn="+warning)
	}
	var form = make(url.Values)
	form.Add("msg", msg)
	resp, err := http.PostForm(wxchatURL+"/?"+strings.Join(params, "&"), form)
	logrus.Info(wxchatURL + "/?" + strings.Join(params, "&") + "  msg:" + msg)
	if err != nil {
		logrus.Error("sendmsg error: ", resp.Status+" "+err.Error())
	}
}

// Run 运行7*24
func Run() {
	var curDay = time.Now().AddDate(0, 0, -1).Format("20060102") // 前一日
	for {
		// 取当前交易日
		row := dbCrms.QueryRow(`SELECT "DAY" FROM SOURCETMP.T_CALENDAR WHERE TRA = 1 AND "DAY" > :day ORDER BY "DAY"`, curDay)
		if err = row.Err(); err != nil {
			logrus.Error("query tradingday error " + err.Error())
			sendMsg("", err.Error(), "", "query tradingday error")
			time.Sleep(1 * time.Hour)
			continue
		}
		var tradingDay string
		err = row.Scan(&tradingDay)
		if err != nil {
			logrus.Error("scan tradingday error " + err.Error())
			sendMsg("", err.Error(), "", "scan tradingday error")
			time.Sleep(1 * time.Hour)
			continue
		}

		// 时间未到，等待
		monitorTime, _ := time.ParseInLocation("20060102 15:04:05", tradingDay+" 15:00:00", time.Local)
		for time.Now().Local().Before(monitorTime) {
			time.Sleep(15 * time.Minute)
			continue
		}
		curDay = tradingDay

		// 取信号数据
		var msg string
		row = dbSign.QueryRow(`select count(1) from public.strategy_sign where tradingday = $1`, tradingDay)
		if err = row.Err(); err != nil {
			logrus.Error("query records error " + err.Error())
			sendMsg("", err.Error(), "", "uery records error")
			time.Sleep(1 * time.Hour)
			continue
		}
		var rowCount int
		row.Scan(&rowCount)
		if rowCount == 0 {
			msg = "no records on " + tradingDay
			logrus.Info(msg)
			sendMsg("", msg, "", "警告")
		} else {
			msg = fmt.Sprintf("%d records on %s", rowCount, tradingDay)
			rows, _ := dbSign.Query(`select strategy_group, instrument, count(1) cnt
			from public.strategy_sign ss 
			where tradingday = $1
			group by strategy_group, instrument 
			order by cnt desc `, tradingDay)
			msg += fmt.Sprintf(`\n   策  略   |  合 约 |信号量`)
			for rows.Next() {
				var stra, inst string
				var cnt int64
				rows.Scan(&stra, &inst, &cnt)
				msg += fmt.Sprintf(`\n%12s|%7s |%4d  `, stra, inst, cnt)
			}
			logrus.Info(msg)
			sendMsg("正常运行", msg, "", "")
		}
	}
}
